package com.atos.smp.actions;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.application.FacesMessage.Severity;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import net.codeissue.web.common.ServiceFinder;

import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;

import com.atos.smp.beans.Collaborator;
import com.atos.smp.business.CollaboratorManager;
import com.atos.smp.business.impl.CollaboratorManagerImpl;
import com.atos.smp.dao.CollaboratorDao;

@ManagedBean
@SessionScoped
public class FileUploadController {

	private Workbook workbook;
	private CollaboratorManager collaboratorManager;

	public FileUploadController() {
		collaboratorManager = Action.getCollaboratorManager();
	}

	public void handleFileUpload(FileUploadEvent event) {
		UploadedFile uploadedFile = event.getFile();

		try {
			workbook = Workbook.getWorkbook(uploadedFile.getInputstream());
		} catch (Exception e) {
			e.printStackTrace();
		}

		Sheet sheet = workbook.getSheet(0);

		Severity summary = FacesMessage.SEVERITY_INFO;
		String content = event.getFile().getFileName() + " is uploaded.";
		try {
			Collaborator collaborator = null;
			
			int i = 5;
			while (!sheet.getCell("A"+i).getContents().isEmpty()){
				collaborator = new Collaborator();
				
				Cell das = sheet.getCell("A"+i); 
				Cell birthday = sheet.getCell("B"+i); 
				Cell email = sheet.getCell("C"+i); 
				Cell firstName = sheet.getCell("D"+i); 
				Cell lastName = sheet.getCell("E"+i); 
				Cell password = sheet.getCell("F"+i); 
				Cell sex = sheet.getCell("G"+i); 
				Cell nationalite = sheet.getCell("H"+i);
				
				// Before do anything the das column has to be filled
				if(!isEmpty(das.getContents())) {
					collaborator.setDas(das.getContents());
					
					Collaborator c = collaboratorManager.findCollaboratorByDas(das.getContents());
					// Check if the collabotor does not already exist
					if(isEmpty(c)) {
						if(!isEmpty(birthday.getContents())){
							
						}
						
						if(!isEmpty(email)) {
							collaborator.setEmail(email.getContents());
						}
						
						if(!isEmpty(firstName)) {
							collaborator.setFirstName(firstName.getContents());
						}
						
						if(!isEmpty(lastName)) {
							collaborator.setLastName(lastName.getContents());
						}
						
						if(!isEmpty(password)) {
							collaborator.setLastName(lastName.getContents());
						}
						
						if(!isEmpty(sex)) {
							collaborator.setSex(sex.getContents());
						}
						
						if(!isEmpty(nationalite)) {
							collaborator.setNationality(nationalite.getContents());
						}
						
						// Add the Collaborator
						collaboratorManager.save(collaborator);
					}
					else {
						summary = FacesMessage.SEVERITY_FATAL;
						content = "Error while uploading, '" + das.getContents() + "' does already exist!";
						break;
					}
				}
				
				i++;
			}
		}catch(Exception e) {
			// TODO While expression
//			summary = FacesMessage.SEVERITY_FATAL;
//			content = "Error while uploading ";
		}
		
		FacesMessage msg = new FacesMessage(summary, "", content);
		FacesContext.getCurrentInstance().addMessage(null, msg);
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		CollaboratorsBean bean = (CollaboratorsBean) session.getAttribute("collaboratorsBean");
		bean.setUpdate(true);
		//session.setAttribute("collaboratorsBean",bean);
		
	}

	public static File inputStreamToFile(InputStream inputStream) {
		File f = null;
		try
		{
			f = new File("outFile.xlsx");
			OutputStream out=new FileOutputStream(f);
			byte buf[]=new byte[1024];
			int len;

			while((len=inputStream.read(buf))>0)
				out.write(buf,0,len);
			out.close();
			inputStream.close();
			System.out.println(" File is created");
		}
		catch (IOException e) {
			System.out.println(e.getMessage());
		}

		return f;
	}

	public static boolean isEmpty(Object value) {
		if (value == null) {
			return true;
		}

		if (value instanceof String) {
			if (((String) value).length() == 0) {
				return true;
			}
		} else if (value instanceof Collection) {
			if (((Collection) value).size() == 0) {
				return true;
			}
		} else if (value instanceof Map) {
			if (((Map) value).size() == 0) {
				return true;
			}
		}
		return false;
	}
}
